package com.seata.demo.service.impl;

import java.math.BigDecimal;

import com.seata.demo.common.exception.AppException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import com.seata.demo.service.AccountService;
import com.seata.demo.common.res.Resp;

import io.seata.core.context.RootContext;
import io.seata.tm.api.GlobalTransactionContext;

import com.seata.demo.mapper.AccountTblMapper;
import com.seata.demo.model.AccountTbl;

import lombok.extern.slf4j.Slf4j;

/**
* @comments
* @author  zg
* @date 2021年2月9日
*/
@AllArgsConstructor
@Slf4j
@Service
public class AccountServiceImpl implements AccountService {
    
    private AccountTblMapper accountTblMapper;
    
    @Override
    public Resp<?> deductBalance(String userId, BigDecimal deductMoney) {
        //String xid = RootContext.getXID();
        //String xid1 = GlobalTransactionContext.getCurrentOrCreate().getXid();
        //log.info("xid={}, xid1={}", xid, xid1);
        AccountTbl account = accountTblMapper.selectByUserId(userId);
        if(account == null) {
            log.warn("用户id不存在。userId={}", userId);
            throw new AppException("用户id不存在");
        }
        BigDecimal balanceMoney = account.getMoney();
        BigDecimal diffVal = balanceMoney.subtract(deductMoney);
        if(diffVal.compareTo(BigDecimal.ZERO) < 0) {
            log.warn("账户余额不足。userId={}, balanceMoney={}, deductMoney={}", userId, balanceMoney, deductMoney);
            //return Resp.error("余额不足");
            throw new AppException("余额不足");
        }
        
        if(accountTblMapper.deductBalance(userId, deductMoney) > 0) {
            log.info("账户扣款成功。userId={}, balanceMoney={}, deductMoney={}", userId, balanceMoney, deductMoney);
            return Resp.success();
        }else {
            account = accountTblMapper.selectByUserId(userId);
            log.warn("账户余额不足，扣款失败。userId={}, balanceMoney={}, deductMoney={}", userId, account.getMoney(), deductMoney);
            //return Resp.error("余额不足，扣款失败");
            throw new AppException("余额不足，扣款失败");
        }
    }


}
